<?php
namespace app\index\controller;
use app\model\Orderc as OrdercModel;
use app\model\Ordera as OrderaModel;
use app\model\Orders as OrdersModel;
use app\model\Orderg as OrdergModel;

use think\Db;

class Payment extends Base
{   
    // 'pay','webPay',
    protected $noCheckToken = ['payCallback','payCallbackWeb'];

    public function pay(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        $fields = [
            'must'=>['uuid','type'],
            'nomust'=>[]
        ];

        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            return apiResult('5000',$params['error_msg']);
        }
        // $params['type'] = 'ordera';
        // $params['uuid'] = '11A47516DDE7481E853A1D3E8FC109DA';

        $uuids = explode(',',$params['uuid']);
        switch ($params['type']) {
            case 'ordera':
                $model = new OrderaModel();
                break;
            case 'orders':
                $model = new OrdersModel();
                break;
            case 'orderg':
                $model = new OrdergModel();
                break;
            default:
                $model = new OrdercModel();
                break;
        }

        $list = $model->where('uuid','in',$uuids)->select()->toarray();
        foreach ($list as $k => $vo) {
            if ($vo['status'] != 0) {
                return apiResult('5000','含有已支付订单');
            }
        }
        $pay_sns = array_column($list, 'pay_sn');
        $pay_sns = array_unique($pay_sns);
        if (count($pay_sns) > 1) {
            return apiResult('5000','已有订单发起过支付');
        }
        if (empty($pay_sns[0])) {
            $pay_sn = uuidCreate();
            $model->where('uuid','in',$uuids)->update(['pay_sn'=>$pay_sn]);
        }else{
            $pay_sn = $pay_sns[0];
        }
        $total_price = array_sum(array_column($list,'total_price'));
        $total_price = $total_price * 100; // 单位分
        if ($total_price <= 0) {
            return apiResult('5000','订单金额异常');
        }
        $config = config('config.stripe');
        $stripe = new \Stripe\StripeClient($config['sk']);
        $customer = $stripe->customers->create();
        $ephemeralKey = $stripe->ephemeralKeys->create([
          'customer' => $customer->id,
        ], [
          'stripe_version' => '2022-08-01',
        ]);
        $paymentIntent = $stripe->paymentIntents->create([
            'amount' => $total_price,
            'currency' => 'hkd',
            'customer' => $customer->id,
            'metadata' => [
                'pay_sn' => $pay_sn,
                'type'=>$params['type']
            ],
            'automatic_payment_methods' => [
                'enabled' => 'true',
                // 'allow_redirects' => 'never'
            ],
            // 'confirm'=>true
            // 'payment_method_types'=>['card','alipay']
        ]);
        // dump($paymentIntent);
        // $confirm = $stripe->paymentIntents->confirm(
        //   $paymentIntent->client_secret,
        //   [
        //     'payment_method' => 'pm_card_visa',
        //     'return_url' => 'https://www.example.com',
        //   ]
        // );
        // dump($confirm);die;
        

        $result = [
            'paymentIntent' => $paymentIntent->client_secret,
            'ephemeralKey' => $ephemeralKey->secret,
            'customer' => $customer->id,
            'publishableKey' => $config['pk']
        ];

        return apiResult('2000','获取支付信息',$result);
    }

    public function webPay(){
        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        $fields = [
            'must'=>['uuid','type','success_url','cancel_url'],
            'nomust'=>[]
        ];

        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            return apiResult('5000',$params['error_msg']);
        }
        // $params['type'] = 'ordera';
        // $params['uuid'] = '11A47516DDE7481E853A1D3E8FC109DA';
        // $params['success_url'] = 'http://www.baidu.com';
        // $params['cancel_url'] = 'http://www.baidu.com';

        $uuids = explode(',',$params['uuid']);
        switch ($params['type']) {
            case 'ordera':
                $model = new OrderaModel();
                break;
            case 'orders':
                $model = new OrdersModel();
                break;
            case 'orderg':
                $model = new OrdergModel();
                break;
            default:
                $model = new OrdercModel();
                break;
        }

        $list = $model->where('uuid','in',$uuids)->select()->toarray();
        foreach ($list as $k => $vo) {
            if ($vo['status'] != 0) {
                return apiResult('5000','含有已支付订单');
            }
        }
        $pay_sns = array_column($list, 'pay_sn');
        $pay_sns = array_unique($pay_sns);
        if (count($pay_sns) > 1) {
            return apiResult('5000','已有订单发起过支付');
        }
        if (empty($pay_sns[0])) {
            $pay_sn = uuidCreate();
            $model->where('uuid','in',$uuids)->update(['pay_sn'=>$pay_sn]);
        }else{
            $pay_sn = $pay_sns[0];
        }
        $total_price = array_sum(array_column($list,'total_price'));
        $total_price = $total_price * 100; // 单位分
        if ($total_price <= 0) {
            return apiResult('5000','订单金额异常');
        }
        $config = config('config.stripe');

        $stripe = new \Stripe\StripeClient($config['sk']);
        $checkout_session = $stripe->checkout->sessions->create([
          'line_items' => [[
            'price_data' => [
              'currency' => 'hkd',
              'product_data' => [
                'name' => 'T-shirt',
              ],
              'unit_amount' => $total_price,
            ],
            'quantity' => 1,
          ]],
          'metadata' => [
                'pay_sn' => $pay_sn,
                'type'=>$params['type']
            ],
          'mode' => 'payment',
          'success_url' => $params['success_url'],
          'cancel_url' => $params['cancel_url'],
          // 'payment_method_types'=>['card','alipay']
        ]);

        return apiResult('2000','获取支付信息',$checkout_session->url);
    }

    public function payCallback(){
        $config = config('config.stripe');
        $stripe = new \Stripe\StripeClient($config['sk']);

        // This is your Stripe CLI webhook secret for testing your endpoint locally.
        $endpoint_secret = $config['endpoint_secret'];

        $payload = @file_get_contents('php://input');
        Db::name('test')->insert(['content'=>'payload-----------'.$payload]);
        $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        $event = null;

        try {
          $event = \Stripe\Webhook::constructEvent(
            $payload, $sig_header, $endpoint_secret
          );
          Db::name('test')->insert(['content'=>'event-----------'.json_encode($event)]);
        } catch(\UnexpectedValueException $e) {
            echo 'Invalid payload';
            exit();
        } catch(\Stripe\Exception\SignatureVerificationException $e) {
            echo 'Invalid signature';
            exit();
        }



        if ($event['type'] == 'payment_intent.succeeded' && $event['data']['object']['status'] == 'succeeded') {
            $object = $event['data']['object'];
            $pay_sn = $object['metadata']['pay_sn'];
            $type = $object['metadata']['type'];
            switch ($type) {
                case 'ordera':
                    $model = new OrderaModel();
                    break;
                case 'orders':
                    $model = new OrdersModel();
                    break;
                case 'orderg':
                    $model = new OrdergModel();
                    break;
                default:
                    $model = new OrdercModel();
                    break;
            }
            $list = $model->where('pay_sn',$pay_sn)->select();
            foreach ($list as $k => $vo) {
                if ($vo['status'] != 0) {
                    continue;
                }
                $save_data = [
                    'status'=>1,
                    'trade_no'=>$object['id'],
                    'pay_time'=>date('Y-m-d H:i:s')
                ];
                $model->where('uuid',$vo['uuid'])->update($save_data);
                // 如果是课程套餐，则同步套餐课程
                if ($type == 'orderc' && $vo['course_type'] == 1) {
                    OrdercModel::where([
                        ['package_uuid','=',$vo['uuid']],
                        ['status','=',0]
                    ])->update($save_data);
                }
            }
        }
    }

    public function payCallbackWeb(){
        $config = config('config.stripe');
        $stripe = new \Stripe\StripeClient($config['sk']);

        // This is your Stripe CLI webhook secret for testing your endpoint locally.
        $endpoint_secret = $config['endpoint_secret'];

        $payload = @file_get_contents('php://input');
        Db::name('test')->insert(['content'=>'payload-----------'.$payload]);
        $sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
        $event = null;

        try {
          $event = \Stripe\Webhook::constructEvent(
            $payload, $sig_header, $endpoint_secret
          );
          Db::name('test')->insert(['content'=>'event-----------'.json_encode($event)]);
        } catch(\UnexpectedValueException $e) {
            echo 'Invalid payload';
            exit();
        } catch(\Stripe\Exception\SignatureVerificationException $e) {
            echo 'Invalid signature';
            exit();
        }


        if ($event['type'] == 'checkout.session.completed' && $event['data']['object']['status'] == 'complete') {
            $object = $event['data']['object'];
            $pay_sn = $object['metadata']['pay_sn'];
            $type = $object['metadata']['type'];
            switch ($type) {
                case 'ordera':
                    $model = new OrderaModel();
                    break;
                case 'orders':
                    $model = new OrdersModel();
                    break;
                default:
                    $model = new OrdercModel();
                    break;
            }
            $list = $model->where('pay_sn',$pay_sn)->select();
            foreach ($list as $k => $vo) {
                if ($vo['status'] != 0) {
                    continue;
                }
                $save_data = [
                    'status'=>1,
                    'trade_no'=>$object['id'],
                    'pay_time'=>date('Y-m-d H:i:s')
                ];
                $model->where('uuid',$vo['uuid'])->update($save_data);
                // 如果是课程套餐，则同步套餐课程
                if ($type == 'orderc' && $vo['course_type'] == 1) {
                    OrdercModel::where([
                        ['package_uuid','=',$vo['uuid']],
                        ['status','=',0]
                    ])->update($save_data);
                }
            }
        }
    }


}
